<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */

namespace app\service\fetch\ocean;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\enum\OeEnum;
use app\model\ClientAccountModel;
use app\model\mysql\OeToolsGrayModel;
use app\model\OeVideoModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\ocean\AdvertiserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\Model;

class ToolsGrayService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_LOCK_KEY]['tools_gray'];

    /**
     * 获取白名单能力.
     * @param string $advertiserId 广告主id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function getToolsGray(string $advertiserId = ''): bool
    {
        // 获取账户信息
        $obj = AccountService::getAccountModel(0, $advertiserId);
        if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
            return self::setError('账户数据不存在');
        }
        $grayKeys = OeEnum::GRAY_KEYS;
        foreach ($grayKeys as $grayKey) {
            $result = self::getList($advertiserId, $grayKey);
            if ($result === false) {
                return false;
            }
            if (count($result['data']['list']) == 0) {
                continue;
            }
            foreach ($result['data']['list'] as $item) {
                $model = self::getInfo($obj->getKey(), $item['gray_key'], intval($item['in_whitelist']));
                if (! $model instanceof OeToolsGrayModel || ! $model->getKey()) {
                    $model = new OeToolsGrayModel();
                }
                $item['account_id'] = $obj->getKey();
                $item['advertiser_id'] = $advertiserId;
                $model->setAttrs($item);
                if (! $model->save()) {
                    return self::setError('保存信息出错');
                }
            }
        }
        return true;
    }

    /**
     * 拉取信息.
     * @param string $advertiserId 账户id
     * @return bool|mixed|string
     * @throws Exception
     */
    private static function getList(string $advertiserId = '', string $grayKey = '')
    {
        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'gray_keys' => [$grayKey],
        ];
        return AdvertiserService::getToolsGray($headers, $params);
    }

    /**
     * 获取白名单能力信息.
     *
     * @param int $accountId 账户id
     * @param string $grayKey 白名单能力key
     * @param int $inWhitelist 白名单能力状态
     * @return null|array|mixed|Model|OeVideoModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(int $accountId = 0, string $grayKey = '', int $inWhitelist = 0)
    {
        $where = [
            ['account_id', '=', $accountId],
            ['gray_key', '=', $grayKey],
            ['in_whitelist', '=', $inWhitelist],
        ];
        return (new OeToolsGrayModel())->where($where)->field(true)->find();
    }
}
